<?php

namespace App\Http\Controllers\Business;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Http\Controllers\Controller;
use App\Models\Business\DepartmentBasicQuote;
use Illuminate\Http\Request;

class DepartmentQuoteController extends Controller
{
    use ModelSearchTrait;

    //
    public function index(Request $request,DepartmentBasicQuote $basicQuote)
    {
        //
        $basicQuote=$this->singleModelSearch($request,$basicQuote,$this->listCondition());
        $basicQuote=$basicQuote->with($this->modelWith());
        $quotes=$basicQuote->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success($quotes);
    }
    //
    public function listCondition()
    {
        return [
            ['quote_name','like'],
            ['department_id','=']
        ];
    }

    //
    public function modelWith()
    {
        return ['department','serviceCategory','oldServiceCategory'];
    }

    //
    public function store(Request $request)
    {
        //
        $data=$request->all();
        $quote=DepartmentBasicQuote::create($data);
        return $this->success(['msg'=>'添加成功','id'=>$quote->id]);
    }

    //
    public function update(Request $request,DepartmentBasicQuote $basicQuote)
    {
        $data=$request->except('quote_id');
        $quote=$basicQuote->find($request->quote_id);
        if(empty($quote)){
            return $this->failed('id错误，无此数据',201);
        }
        $quote=$this->oldData($data,$quote);
        $quote->fill($data)->save();
        return $this->success(['msg'=>'编辑成功']);
    }
    //
    public function oldData($data,$quote){
        if($quote->service_cate_id!=$data['service_cate_id']){
            $quote->old_service_cate_id=$quote->service_cate_id;
        }
        if($quote->price_content!=$data['price_content']){
            $quote->old_price_content=$quote->price_content;
        }
        return $quote;
    }

    //
    public function destroy(Request $request,DepartmentBasicQuote $basicQuote)
    {
        $quote=$basicQuote->find($request->quote_id??0);
        if(empty($quote)){
            return $this->failed('id错误，无此数据',201);
        }
        $quote->delete();
        return $this->success(['msg'=>'删除成功']);
    }
    //
    public function getAllQuotes(Request $request,DepartmentBasicQuote $basicQuote){
        $basicQuote=$this->singleModelSearch($request,$basicQuote,$this->listCondition());
        $quotes=$basicQuote->with($this->modelWith())->get();
        return $this->success($quotes);
    }


}
